from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from cart.utils import merge_cookie_cart_to_redis
from oauth.exceptions import QQAPIError
from oauth.models import OAthQQUser
from oauth.serializers import QQAuthUserSerializer
from oauth.utils import OAuthQQ
from rest_framework.views import APIView

# /oauth/qq/user/?code=<code>
class QQAuthUserView(GenericAPIView):
    serializer_class = QQAuthUserSerializer
    def post(self, request):
        """
        保存QQ登录绑定数据:
        1. 获取参数并进行校验(参数完整性，手机号格式，短信验证码是否正确，access_token是否有效)
        2. 保存QQ绑定的数据并生成jwt token
        3. 返回应答，绑定成功
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        response = Response(serializer.data, status=status.HTTP_201_CREATED)
        # 调用合并购物车记录函数
        user = self.user
        merge_cookie_cart_to_redis(request, user, response)
        return response

    def get(self, request):
        '''
        获取QQ登录用户openid并处理：
        1. 获取code并校验(code必传)
        2. 获取QQ登录用户的openid
            2.1 通过code请求QQ服务器获取access_token
            2.2 通过access_token请求QQ服务器获取openid
        3. 根据openid判断是否绑定过本网站的用户
            3.1 如果已绑定，直接生成jwt token并返回
            3.2 如果未绑定，将openid加密并返回
        '''
        # 1. 获取code并校验(code必传)
        code = request.query_params.get('code')
        if code is None:
            return Response({'message':'缺少code参数'}, status=status.HTTP_400_BAD_REQUEST)
        oauth = OAuthQQ()
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_openid(access_token)
        except QQAPIError:
            return Response({'message': 'QQ登录异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 3.根据openid判断是否绑定过本网站的用户
        try:
            qq_user = OAthQQUser.objects.get(oppenid=openid)
        except OAthQQUser.DoesNotExist:
            secret_openid = OAuthQQ.generate_save_user_token(openid)
            return Response({'access_token': secret_openid})
        else:
            user = qq_user.user
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            userdata = {'user_id':user.id, 'username': user.username,
                        'token': token}
            response = Response(userdata)

            # 调用合并购物车记录函数
            merge_cookie_cart_to_redis(request, user, response)
            return response
# /oauth/qq/authorization/?next=<登录之后访问页面地址>
class QQAuthURLView(APIView):
    """
    QQ登录第一步,获取登录qq的网址
    """
    def get(self, request):
        # 获取参数next,用户从哪个页面进去登录页面进行qq登录
        next = request.query_params.get('next')
        # 组织参数,获取网址 ,将state设置成next
        oauth = OAuthQQ(state=next)
        # 返回地址
        return Response({'login_url': oauth.get_login_url()})
